<template>
<div v-loading="isloading" class="beian-container">
    <el-dialog :title="
        dialogStatus == 'add' ? '底图底数领取记录新增' : '底图底数领取记录编辑'
      " :visible.sync="isDialogShow" width="550px" :append-to-body="true" class="dialog1">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="left">
            <el-form-item label="行政区划选择:" prop="villageIds">
                <el-cascader style="width: 300px" v-model="form.villageIds" :options="citylist" :props="props" size="medium" placeholder="请选择行政区划" clearable collapse-tags :show-all-levels="false" @change="handleChange"></el-cascader>
            </el-form-item>

            <el-form-item label="领取区县机构:" prop="receiveOrganization">
                <el-input type="text" :rows="2" placeholder="请输入领取机构名称" size="mini" clearable v-model="form.receiveOrganization" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="领取人:" prop="receiveName">
                <el-input type="text" :rows="2" placeholder="请输入领取人名" size="mini" clearable v-model="form.receiveName" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="联系方式:" prop="receivePhone">
                <el-input type="text" :rows="2" placeholder="请输入正确的电话号码" size="mini" clearable v-model="form.receivePhone" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item label="领取时间:" prop="receiveDate">
                <el-date-picker v-model="form.receiveDate" type="date" style="width: 300px" placeholder="选择日期"></el-date-picker>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="isDialogShow = false">取 消</el-button>
            <el-button type="primary" @click="dialogStatus === 'add' ? submitForm('form') : updateData()">提交</el-button>
        </span>
    </el-dialog>
    <div>
        <div class="header">
            <i class="el-icon-d-arrow-right"></i>底图底数领取新增
        </div>
        <div class="header-button">
            <el-tooltip class="item" effect="dark" :content="'未领取底图数' + options.length" placement="bottom-start">
                <!-- <el-badge :value="options.length" class="item" type="primary"> -->
                <el-button type="danger" @click="open">
                    <i class="el-icon-plus"></i>添加
                </el-button>
                <!-- </el-badge> -->
            </el-tooltip>
            <el-button type="primary" @click="download">
                <i class="el-icon-download"></i>导出
            </el-button>
        </div>
    </div>
    <div class="header">
        <i class="el-icon-d-arrow-right"></i>底图底数领取备案
    </div>
    <el-table :data="tableData" stripe border style="width: 100%" class="eltable">
        <el-table-column label="序号" width="80" type="index" />
        <el-table-column prop="villages" label="被领取村庄">
            <template slot-scope="scope">
                <div v-if="scope.row.villages.length > 0">
                    <span>{{ scope.row.villages[0] }}</span><span class="vitotal" v-if="scope.row.villages.length > 1">等共{{ scope.row.villages.length }}个村庄</span>

                    <a class="more" href="#" @click="openMore(scope.row.villages)">查看更多<i class="el-icon-d-arrow-right" /></a>
                </div>
                <div v-if="scope.row.villages.length == 0">无</div>
            </template>
        </el-table-column>

        <el-table-column prop="receiveOrganization" label="领取区县机构" width="150" />
        <el-table-column prop="receiveName" label="领取人" width="150" />
        <el-table-column prop="receivePhone" label="联系方式" width="150" />
        <el-table-column prop="receiveDate" label="领取时间 " width="180" />
        <el-table-column prop="recordUserName" label="发放人" width="150" />
        <el-table-column label="操作" width="225" align="center" fixed="right">
            <template slot-scope="scope">
                <el-button type="primary" @click="handleUpdate(scope.row)" size="mini" plain>
                    <i class="el-icon-edit"></i>编辑
                </el-button>
                <el-button type="danger" @click="handleDelete(scope.row.id)" size="mini" plain>
                    <i class="el-icon-delete"></i>删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination v-if="tableData.length > 0" class="elpagi" :total="total" @size-change="getdata" @current-change="getdata" @prev-click="getdata" @next-click="getdata" :current-page.sync="listquery.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size.sync="listquery.pageSize" layout="total,sizes, prev, pager, next, jumper" />
    <el-dialog title="村庄列表" :visible.sync="dialogVisible" width="30%" append-to-body :close-on-click-modal="false">
        <ul class="villageul">
            <div class="allvilagestitle">领取村庄列表如下所示:</div>
            <li v-for="item in allvilages" :key="item">{{ item }}</li>
        </ul>
    </el-dialog>
</div>
</template>

<script>
import {
    handleCofirm
} from "@/utils/confirm";
import {
    export_json_to_excel
} from "@/utils/export2Excel.js";
import {
    getTownList,
    getAllVillageList,
    getlist,
    getlistdown,
    getlistall,
    add,
    edit,
    del,
} from "@/api/country.js";
import {
    mapGetters
} from 'vuex'
export default {
    computed: {
        ...mapGetters([
            'citylist',
        ])
    },

    data() {
        return {
            villageIds: [],
            total: 0,
            dialogStatus: "",
            options1: [],
            citySelected: "",
            citySelectedShow: true,
            props: {
                lazy: true,
                lazyLoad: this.lazyLoad,
                multiple: true,
            },
            dialogVisible: false,
            form: {
                receiveOrganization: "",
                target: "",
                villageIds: [],
                receivePhone: "",
                receiveName: "",
                receiveDate: "",
            },
            rules: {
                villageIds: [{
                    required: true,
                    message: "请选择领取区域",
                    trigger: "blur"
                }, ],
                receivePhone: [{
                    required: true,
                    message: "请输入联系人电话号码",
                    trigger: "blur"
                }, ],
                receiveOrganization: [{
                    required: true,
                    message: "请输入领取区县机构",
                    trigger: "blur"
                }, ],
                receiveName: [{
                    required: true,
                    message: "请输入领取人名称",
                    trigger: "blur"
                }, ],
                receiveDate: [{
                    required: true,
                    message: "请选择领取时间",
                    trigger: "blur"
                }, ],
            },
            tableData: [],
            options: [],
            isloading: false,
            role: "",
            nowuserarea: "",
            isDialogShow: false,
            listquery: {
                pageSize: 10,
                currentPage: 1,
                userType: 1,
            },
            allvilages: [],
        };
    },
    mounted() {
        this.getdata();
    },
    methods: {
        handleChange(e) {},
        download() {
            this.isloading = true;
            let query = {
                pageSize: 9999,
                currentPage: 1,
            };
            getlistdown(query).then((res) => {
                let tablelist = res.data.content;
                this.downloadExcel(tablelist);
                this.isloading = false;
            });
        },
        downloadExcel(tabledatalist) {
            // let header = Object.keys(tabledatalist[0]);
            // let list2 = [];
            // for (var i = 0; i < tabledatalist.length; i++) {
            //   let list1 = [];
            //   for (var j = 0; j < header.length; j++) {
            //     let obj = tabledatalist[i];
            //     list1.push(obj[header[j]]);
            //   }
            //   list2.push(list1);
            // }
            const tHeader = [
                '市',
                '区县',
                '乡镇',
                '村庄',
                '领取人',
                '领取机构',
                '领取人电话',
                '领取时间',
            ]
            const filterVal = [
                'city',
                'country',
                'town',
                'village',
                'receiveName',
                'receiveOrganization',
                'receivePhone',
                'receiveDate',
            ]
            const data = this.formatJson(filterVal, tabledatalist)
            export_json_to_excel({
                header: tHeader,
                data,
                filename: "底图底数领取备案记录",
            });
        },
        formatJson(filterVal, listdata) {
            return listdata.map((v) =>
                filterVal.map((j) => {
                    if (j === 'timestamp') {
                        return parseTime(v[j])
                    } else {
                        return v[j]
                    }
                })
            )
        },
        async getdata() {
            this.isloading = true;
            let res = await getlist(this.listquery);
            this.tableData = res.data.content;
            this.total = res.data.totalElements;
            this.isloading = false;
        },
        openMore(villages) {
            this.dialogVisible = true;
            this.allvilages = villages;
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const temp = Object.assign({}, this.form);
                    let villageIds = this.form.villageIds.map((v) => {
                        return v[3];
                    });
                    temp.villageIds = villageIds.toString();
                    temp.userType = 1
                    add(temp)
                        .then((v) => {
                            this.getdata();
                            this.$notify({
                                title: "成功",
                                message: "添加成功",
                                type: "success",
                            });
                            this.isDialogShow = false;
                        })
                        .catch((error) => {
                            this.$notify.error({
                                title: "错误",
                                message: error,
                            });
                        });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },

        handleUpdate(row) {
            this.form = Object.assign({}, row); // copy obj
            let list = this.form.villageIds.split(",")
            let list1 = []
            list.forEach(element => {
                list1.push([undefined, undefined, undefined, element])
            });
            this.form.villageIds = list1

            this.dialogStatus = "edit";
            this.isDialogShow = true;
            this.$nextTick(() => {
                this.$refs["form"].clearValidate();
            });
        },
        updateData() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    const temp = Object.assign({}, this.form);

                    let villageIds = this.form.villageIds.map((v) => {
                        return v[3];
                    });
                    temp.villageIds = villageIds.toString();
                    edit(temp).then(() => {
                        this.getdata();
                        this.isDialogShow = false;
                        this.$notify({
                            title: "成功",
                            message: "修改成功",
                            type: "success",
                            duration: 2000,
                        });
                    });
                }
            });
        },
        handleDelete(id) {
            handleCofirm("确认要删除吗？", "warning").then((res) => {
                del(id)
                    .then((v) => {
                        this.getdata();
                        this.$notify({
                            title: "成功",
                            message: "删除成功",
                            type: "success",
                        });
                        this.isDialogShow = false;
                    })
                    .catch((error) => {
                        this.$notify.error({
                            title: "错误",
                            message: error,
                        });
                    });
            });
        },
        open() {
            this.form = {
                area: this.nowuserarea,
                target: "",
                villageIds: [],
                receiveName: "",
                receiveDate: "",
            };
            this.dialogStatus = "add";
            this.$nextTick(() => {
                this.$refs["form"].clearValidate();
            });
            this.isDialogShow = true;
        },
        lazyLoad(node, resolve) {
            let level = node.level;
            if (level == 2) {
                let country = node.label;
                let city = node.parent.label;
                getTownList({
                    city: city,
                    country: country,
                }).then((res) => {
                    let nodes = [];
                    let promiseArrary = [];
                    res.data.map((v, i) => {
                        let n = {
                            id: i,
                            label: v,
                            value: v,
                            children: [],
                        };
                        let promise = getAllVillageList({
                            city: city,
                            country: country,
                            town: v,
                        }).then((response) => {
                            return response;
                        });
                        promiseArrary.push(promise);
                        nodes.push(n);
                    });
                    Promise.all(promiseArrary).then((dataArr) => {
                        nodes.forEach((v, i) => {
                            let data = dataArr[i];
                            v.children = data.data.map((item, index) => {
                                return {
                                    id: index,
                                    label: item[1],
                                    value: item[0],
                                    leaf: true,
                                };
                            });
                        });
                        resolve(nodes);
                    });
                });
            } else {
                resolve(node);
            }
        },
    },
};
</script>

<style lang="scss" scoped>
@import "../../../public/css/table.scss";

.villageul {
    margin: 0;
    padding: 5px;
    list-style: none;
    border: 1px dashed #ccc;
    max-height: 250px;
    overflow-y: auto;

    li {
        line-height: 25px;
    }
}

.allvilagestitle {
    line-height: 35px;
    color: #4778c7;
}

.more {
    color: #4cc8c7;
    margin-left: 10px;

    &:hover {
        color: orange;
    }
}

.beian-container {

    height: 100%;
    overflow: auto;
    background-color: #fff;
}

::v-deep .el-header {
    display: flex;
    align-items: center;
    padding: 0px 5px;
}

.item {
    margin-right: 15px;
}

.header-button {
    padding: 10px;
    display: flex;
    justify-content: space-between;
}

.header {
    font-size: 14px;
    font-weight: 600;
    line-height: 35px;
    margin-right: 5px;
    border-bottom: 1px dashed #ccc;

    i {
        color: #4778c7;
    }
}
</style>
